package service

import (
	"communityTopics/repository"
	"errors"
	"unicode/utf8"
)

func PostPublish(userId int64, topicId int64, rootId int64, content *string) (*PostInfo, error) {
	return NewPublishPostFlow(userId, topicId, rootId, content).Do()
}

func NewPublishPostFlow(userId int64, topicId int64, rootId int64, content *string) *PublishPostFlow {
	return &PublishPostFlow{
		userId:  userId,
		topicId: topicId,
		content: content,
		rootId:  rootId,
	}
}

type PublishPostFlow struct {
	userId  int64
	content *string
	topicId int64
	rootId  int64
	postId  int64
	post    *repository.Post
}

func (f *PublishPostFlow) Do() (*PostInfo, error) {
	if err := f.checkParam(); err != nil {
		return &PostInfo{}, err
	}
	if err := f.publish(); err != nil {
		return &PostInfo{}, err
	}
	user, err := repository.NewUserDaoInstance().QueryUserById(f.userId)
	if err != nil {
		return &PostInfo{}, err
	}
	return &PostInfo{
		Post: f.post,
		User: user,
	}, nil
}

func (f *PublishPostFlow) checkParam() error {
	if f.userId <= 0 {
		return errors.New("userId id must be larger than 0")
	}
	if utf8.RuneCountInString(*f.content) >= 500 {
		return errors.New("content length must be less than 500")
	}
	return nil
}

func (f *PublishPostFlow) publish() error {
	f.post = &repository.Post{
		TopicId: f.topicId,
		UserId:  f.userId,
		Content: *f.content,
	}
	if err := repository.NewPostDaoInstance().CreatePost(f.post); err != nil {
		return err
	}
	return nil
}
